<template>
  <div class="categories-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <div class="search-row">
        <div class="search-item">
          <span class="label">分类名称:</span>
          <el-input
            v-model="queryParams.name"
            placeholder="请输入分类名称"
            clearable
          />
        </div>
        <div class="search-item">
          <span class="label">状态:</span>
          <el-select v-model="queryParams.status" placeholder="请选择状态">
            <el-option label="全部" value="all" />
            <el-option label="启用" :value="1" />
            <el-option label="禁用" :value="0" />
          </el-select>
        </div>
        <div class="search-buttons">
          <el-button type="primary" @click="handleSearch" :loading="searchBtnLoading">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </div>
      </div>
    </div>

    <!-- 操作按钮区域 -->
    <div class="toolbar">
      <el-button type="primary" circle @click="handleAdd">
        <el-icon><Plus /></el-icon>
      </el-button>
    </div>
    
    <!-- 表格区域 -->
    <el-table
      :data="categoryList"
      v-loading="loading"
      border
      style="width: 100%; margin-bottom: 20px;"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column prop="name" label="分类名称" min-width="180" />
      <el-table-column prop="sort" label="排序" width="80" align="center" />
      <el-table-column label="状态" width="100" align="center">
        <template #default="{ row }">
          <el-tag :type="row.status === 1 ? 'success' : 'info'" effect="dark">
            {{ row.status === 1 ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" width="170" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.create_time) }}
        </template>
      </el-table-column>
      <el-table-column label="更新时间" width="170" align="center">
        <template #default="{ row }">
          {{ formatDateTime(row.update_time) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" min-width="220" align="center">
        <template #default="{ row }">
          <div class="operation-buttons">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              <span>编辑</span>
            </el-button>
            <el-button 
              :type="row.status === 1 ? 'warning' : 'success'" 
              size="small" 
              @click="handleStatus(row)"
            >
              <el-icon>
                <component :is="row.status === 1 ? 'Bottom' : 'Top'" />
              </el-icon>
              <span>{{ row.status === 1 ? '下架' : '上架' }}</span>
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              <span>删除</span>
            </el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination">
      <el-pagination
        v-model:current-page="pagination.currentPage"
        v-model:page-size="pagination.pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 分类编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      v-model="dialogVisible"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="999" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getCategoryList, createCategory, updateCategory, deleteCategory } from '@/api/category'
import dayjs from 'dayjs'
import { Plus, Edit, Bottom, Top, Delete } from '@element-plus/icons-vue'

const loading = ref(false)
const submitting = ref(false)
const categoryList = ref([])
const dialogVisible = ref(false)
const dialogTitle = ref('')
const currentId = ref(null)
const formRef = ref(null)
const searchBtnLoading = ref(false)

// 分页配置
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

const form = reactive({
  name: '',
  sort: 0,
  status: 1
})

const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入排序号', trigger: 'blur' }
  ]
}

// 搜索表单 - 改名为queryParams保持一致性
const queryParams = reactive({
  name: '',
  status: 'all', // 改为'all'表示全部
  page: 1,
  pageSize: 10
})

// 获取分类列表
const fetchData = async () => {
  try {
    loading.value = true
    searchBtnLoading.value = true
    
    const params = {
      page: pagination.currentPage,
      pageSize: pagination.pageSize
    }
    
    // 只有在有值的情况下才添加参数
    if (queryParams.name) {
      params.name = queryParams.name
    }
    
    // 处理"all"值，与商品管理页保持一致
    if (queryParams.status !== 'all') {
      params.status = queryParams.status
    }
    
    console.log('请求参数:', params)
    const { list, total } = await getCategoryList(params)
    console.log('接口返回数据:', { list, total })
    
    categoryList.value = list
    pagination.total = total
  } catch (error) {
    console.error('获取分类列表失败:', error)
    ElMessage.error(error.message || '获取分类列表失败')
  } finally {
    loading.value = false
    searchBtnLoading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  // 如果按钮已经处于加载状态，不重复发起请求
  if (searchBtnLoading.value) return

  pagination.currentPage = 1
  fetchData()
}

// 重置搜索
const resetSearch = () => {
  // 如果按钮已经处于加载状态，不重复发起请求
  if (searchBtnLoading.value) return

  queryParams.name = ''
  queryParams.status = 'all' // 改为'all'表示全部
  pagination.currentPage = 1
  fetchData()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  pagination.pageSize = val
  fetchData()
}

// 处理页码变化
const handleCurrentChange = (val) => {
  pagination.currentPage = val
  fetchData()
}

// 添加状态切换处理函数
const handleStatus = async (row) => {
  try {
    // 当前状态的反转
    const newStatus = row.status === 1 ? 0 : 1
    console.log(`更新分类[${row.id}]状态, 从 ${row.status} 变为 ${newStatus}`)
    
    await updateCategory(row.id, { status: newStatus })
    
    ElMessage.success('操作成功')
    fetchData()
  } catch (error) {
    console.error('更新分类状态失败:', error)
    ElMessage.error('更新状态失败: ' + (error.message || '服务器错误'))
  }
}

// 新增分类
const handleAdd = () => {
  dialogTitle.value = '新增分类'
  currentId.value = null
  form.name = ''
  form.sort = 0
  form.status = 1
  dialogVisible.value = true
}

// 编辑分类
const handleEdit = (row) => {
  dialogTitle.value = '编辑分类'
  currentId.value = row.id
  form.name = row.name
  form.sort = row.sort
  form.status = row.status
  dialogVisible.value = true
}

// 删除分类
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该分类吗？', '提示', {
      type: 'warning'
    })
    
    await deleteCategory(row.id)
    ElMessage.success('删除成功')
    fetchData()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
    }
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true
    
    const data = currentId.value 
      ? await updateCategory(currentId.value, form)
      : await createCategory(form)

    // 成功处理
    ElMessage.success('操作成功')
    dialogVisible.value = false
    fetchData()
  } catch (error) {
    console.error('操作失败:', error)
  } finally {
    submitting.value = false
  }
}

// 格式化日期时间
const formatDateTime = (datetime) => {
  if (!datetime) return '';
  return dayjs(datetime).format('YYYY-MM-DD HH:mm:ss');
}

onMounted(() => {
  fetchData()
})
</script>

<style scoped>
.categories-container {
  padding: 20px;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}

.search-form {
  margin-bottom: 20px;
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.toolbar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.search-row {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  width: 100%;
}

.search-item {
  display: flex;
  align-items: center;
  margin-right: 15px;
  margin-bottom: 10px;
}

.search-item .label {
  margin-right: 8px;
  white-space: nowrap;
}

.search-item .el-input,
.search-item .el-select {
  min-width: 180px;
}

.search-buttons {
  margin-left: auto;
  display: flex;
  align-items: center;
}

.search-buttons .el-button {
  min-width: 80px;
  margin-left: 10px;
}

.dialog-footer {
  text-align: right;
}

.operation-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  justify-content: center;
}

.operation-buttons .el-button {
  padding: 5px 10px;
  margin: 2px 0;
}

.operation-buttons .el-icon {
  margin-right: 2px;
}

.el-table {
  width: 100% !important;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

/* 表格头部样式 */
:deep(.el-table__header-wrapper th) {
  background-color: #f5f7fa !important;
  color: #606266;
  font-weight: bold;
}

/* 响应式布局调整 */
@media (max-width: 1200px) {
  .search-row {
    flex-wrap: wrap;
  }
  
  .search-buttons {
    margin-left: 0;
    margin-top: 10px;
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 